package com.yuns.course.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yuns.course.dto.CourseDto;
import com.yuns.course.entity.*;
import com.yuns.course.mapper.CourseDocRelMapper;
import com.yuns.course.param.CourseParam;
import com.yuns.course.service.*;
import com.yuns.course.vo.CourseVO;
import com.yuns.study.entity.InfoDocI;
import com.yuns.study.service.IInfoDocIService;
import com.yuns.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 课程类型基础表 服务实现类
 * </p>
 *
 * @author liuChengWen
 * @since 2020-10-26
 */
@Service
public class CourseServiceImpl implements ICourseService {

    @Value("${fastdfs.agent.url}")
    private String FILE_SERVER_URL;//文件服务器地址

    @Resource
    private ICourseBaseService iCourseBaseService;

    @Resource
    private ICourseInfoService courseInfoService;

    @Resource
    private ICourseTypeRelService courseTypeRelService;

    @Resource
    private ICourseDocRelService courseDocRelService;

    @Resource
    private ICourseChapterRelService courseChapterRelService;

    @Resource
    private ICourseChapterService courseChapterService;

    @Resource
    private CourseDocRelMapper courseDocRelMapper;

    @Resource
    private IInfoDocIService infoDocIService;

    @Resource
    private ICourseTypeService courseTypeService;

    /**
     * 课程新增
     *
     * @param model
     * @return
     */
    @Transactional
    @Override
    public boolean insert(CourseDto model) {
        //设定课时
        List<CourseChapter> courseChapterList = model.getCourseChapterList();
        int coursePeriod=0;
        if(courseChapterList.size()>0){
            coursePeriod=courseChapterList.stream().mapToInt(c->c.getPeriod()).sum();
        }
        model.setPeriod(coursePeriod);
        boolean flag = iCourseBaseService.insert(model);
        if (flag) {
            Integer courseType = model.getCourseType();
            //插入课程类型
            CourseTypeRel courseTypeRel = new CourseTypeRel();
            courseTypeRel.setCourseId(model.getId());
            courseTypeRel.setCourseTypeId(courseType);
            courseTypeRelService.insert(courseTypeRel);
            //更新课程类型-绑定课程数量
            CourseType courseTypeBase=courseTypeService.selectById(courseType);
            courseTypeBase.setCourseCount(courseTypeBase.getCourseCount()+1);
            courseTypeService.updateById(courseTypeBase);

            //插入法律法规
            List<InfoDocI> infoDocIList = model.getInfoDocIList();
            if(infoDocIList.size()>0){
                List<CourseDocRel> courseDocRelList = new ArrayList<>();
                for (InfoDocI i : infoDocIList) {
                    CourseDocRel courseDocRel = new CourseDocRel();
                    courseDocRel.setCourseId(model.getId());
                    courseDocRel.setDocId(i.getId());
                    courseDocRelList.add(courseDocRel);
                    i.setCourseCount(i.getCourseCount()+1);
                }
                courseDocRelService.insertBatch(courseDocRelList);
                //更新法律法规绑定的课程数量
                infoDocIService.updateBatchById(infoDocIList);
            }
            //插入章节
            if(courseChapterList.size()>0){
                courseChapterService.insertBatch(courseChapterList);
                List<CourseChapterRel> courseChapterRels = new ArrayList<>();
                for (CourseChapter chapter : courseChapterList) {
                    CourseChapterRel courseChapterRel = new CourseChapterRel();
                    courseChapterRel.setCourseId(model.getId());
                    courseChapterRel.setChapterId(chapter.getId());
                    courseChapterRels.add(courseChapterRel);
                }
                courseChapterRelService.insertBatch(courseChapterRels);
            }

            //插入详情(给定初始值,后面采取计算)
            CourseInfo courseInfo = new CourseInfo();
            courseInfo.setCompleRate("100");
            courseInfo.setPageViews(0);
            courseInfo.setType(1);
            courseInfo.setPid(model.getId());
            courseInfoService.insert(courseInfo);
            return true;
        }
        return false;
    }

    /**
     * 课程保存
     * @param model
     * @return
     */
    @Transactional
    @Override
    public boolean up(CourseDto model) {
        boolean flag = iCourseBaseService.updateById(model);
        if(flag){
            Integer courseType = model.getCourseType();
            /*********修改课程类型*******/
            CourseTypeRel courseTypeRel = new CourseTypeRel();
            courseTypeRel.setCourseId(model.getId());
            courseTypeRel.setCourseTypeId(courseType);
            courseTypeRelService.updateById(courseTypeRel);

            /*********修改法律法规*******/
            //删除之前绑定的法律法规
            List<InfoDocI> infoDocIList = model.getInfoDocIList();
            if(infoDocIList.size()>0){
                EntityWrapper<CourseDocRel> wrapper=new EntityWrapper<>();
                CourseDocRel rel=new CourseDocRel();
                rel.setCourseId(model.getId());
                wrapper.setEntity(rel);
                courseDocRelMapper.delete(wrapper);
                for (InfoDocI i : infoDocIList) {
                    CourseDocRel courseDocRel = new CourseDocRel();
                    courseDocRel.setCourseId(model.getId());
                    courseDocRel.setDocId(i.getId());
                    courseDocRelService.insert(courseDocRel);
                }
            }

            /*********修改章节*******/
            List<CourseChapter> courseChapterList = model.getCourseChapterList();
            if(courseChapterList.size()>0){
                //删除旧的章节
                EntityWrapper<CourseChapterRel> chapterRelEntityWrapper=new EntityWrapper<>();
                CourseChapterRel courseChapterRel=new CourseChapterRel();
                courseChapterRel.setCourseId(model.getId());
                chapterRelEntityWrapper.setEntity(courseChapterRel);
                List<CourseChapterRel> chapterRelList=courseChapterRelService.selectList(chapterRelEntityWrapper);
                List<Integer> ids=new ArrayList<>();
                chapterRelList.stream().forEach(item->{
                    ids.add(item.getChapterId());
                });
                if (ids.size()>0){
                    courseChapterService.deleteBatchIds(ids);
                }
                //插入新的章节
                courseChapterService.insertBatch(courseChapterList);

                /*********修改课程-章节关联关系*******/
                //删除旧的课程-章节关联关系
                courseChapterRelService.delete(chapterRelEntityWrapper);
                //建立新的关联关系
                List<CourseChapterRel> courseChapterRels = new ArrayList<>();
                for (CourseChapter chapter : courseChapterList) {
                    CourseChapterRel chapterRel = new CourseChapterRel();
                    chapterRel.setCourseId(model.getId());
                    chapterRel.setChapterId(chapter.getId());
                    courseChapterRels.add(chapterRel);
                }
                courseChapterRelService.insertBatch(courseChapterRels);
            }
            return true;
        }
        return false;
    }


    /**
     * 课程删除
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public boolean deleteById(Integer id) {
        boolean flag = iCourseBaseService.deleteById(id);
        if (flag) {
            HashMap infoMap = new HashMap<>();
            infoMap.put("pid", id);
            courseInfoService.deleteByMap(infoMap);
            courseChapterRelService.deleteById(id);
            courseDocRelService.deleteById(id);
            HashMap map = new HashMap<>();
            map.put("course_id", id);
            courseTypeRelService.deleteByMap(map);
            //清理文件

            return true;
        }
        return false;
    }

    /**
     * 课程列表查询
     *
     * @param courseParam
     * @return
     */
    @Override
    public List<CourseVO> selectCourseList(CourseParam courseParam) {
        return iCourseBaseService.selectCourseList(courseParam);
    }

    @Override
    public List<CourseVO> selectCourseList( Page<CourseVO> page,CourseParam courseParam) {
        return iCourseBaseService.selectCourseList(page,courseParam);
    }
    @Override
    public void exportList(CourseParam courseParam, HttpServletResponse response) {
        try {
            List<CourseVO> list = iCourseBaseService.selectCourseList(courseParam);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            String fileName = "课程列表" + df.format(new Date()) + ".xls";

            String[] rowsName = new String[]{"序号","课程名","课程类型","上传时间","浏览量","积分","课时","完成率"};
            List<Object[]>  dataList = new ArrayList<Object[]>();
            Object[] objs = null;
            for (int i = 0; i < list.size(); i++) {
                objs = new Object[rowsName.length];
                objs[0] = i;
                objs[1] = list.get(i).getCourseName();
                objs[2] = list.get(i).getCourseType();
                objs[3] = df.format(list.get(i).getUploadTime());
                objs[4] = list.get(i).getPageViews();
                objs[5] = list.get(i).getIntegral();
                objs[6] = list.get(i).getPeriod();
                objs[7] = list.get(i).getCompleRate();
                dataList.add(objs);
            }
            CommonExcel ex = new CommonExcel("课程导出情况", rowsName, dataList,response,fileName);
            ex.downloadExcel();
        }catch (Exception e){
            throw  new RuntimeException("课程列表导出失败");
        }
    }

    /**
     * 编辑查询
     * @param id
     * @return
     */
    @Override
    public CourseVO queryById(Integer id) {
        return iCourseBaseService.queryById(id);
    }

}
